<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>获取抖音视频 (重点操作)</button>
    <script>
        //函数发送AJAX请求  返回 promise 对象
        function sendAJAX(type, url){
            //实例化 promise 对象
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.responseType = 'json';
                xhr.open(type, url);
                xhr.send();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        //判断
                        if(xhr.status >= 200 && xhr.status < 300){
                            //成功  
                            resolve({
                                //响应状态码
                                status: xhr.status,
                                //响应状态字符串
                                statusText: xhr.statusText,
                                //响应头
                                headers: xhr.getAllResponseHeaders(),
                                //响应体
                                data: xhr.response,
                                //请求对象
                                request: xhr
                            });
                        }else{
                            //失败
                            reject(xhr.status);
                        }
                    }
                }
            });
        }
        
        //获取元素
        let btn = document.querySelector('button');

        //绑定事件
        btn.onclick = async function(){
            //1. promise 的写法
            // sendAJAX('get', 'http://api.xiaohigh.com/douyin')
            // .then(res => {
            //     console.log(res);
            // }, err => {
            //     console.log(err);
            // })

            //2. await 的写法
            try{
                let result = await sendAJAX('get', 'http://api.xiaohigh.com/douyin');
                console.log(result);
            }catch(e){
                console.log(e);
            }
        }



    
    </script>
</body>
</html>